package com.example.medicine.controller;


import com.example.medicine.Bean.yian.*;
import com.example.medicine.Bean.zhenghou;
import com.example.medicine.Bean.zhengzhuang;

import com.example.medicine.Mapper.yian.*;
import com.example.medicine.Mapper.yonghuMapper;
import com.example.medicine.Mapper.zhenghouMapper;
import com.example.medicine.Mapper.zhengzhuangMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
@RestController
@RequestMapping(value="/wxya")
public class yianController {

    private static final String UPLOADED_FOLDER = "D:/FileRecv/uploadImages/";
    Subject subject = SecurityUtils.getSubject();
    @Autowired
    private yian_shexiangMapper yian_shexiangMapper;
    @Autowired
    private yian_maizhenMapper yian_maizhenMapper;
    @Autowired
    private zhenghouMapper zhenghouMapper;
    @Autowired
    private zhengzhuangMapper zhengzhuangMapper;
    @Autowired
    private yian_jibingMapper yian_jibingMapper;
    @Autowired
    private yian_jianchaMapper yian_jianchaMapper;
    @Autowired
    private yian_cankaoMapper yian_cankaoMapper;
    @Autowired
    private yian_chufangMapper yian_chufangMapper;
    @Autowired
    private yianMapper yianMapper;
    @Autowired
    private yian_xiyiMapper yian_xiyiMapper;
    @Autowired
    private yian_zhengzhuangMapper yian_zhengzhuangMapper;
    @Autowired
    private yonghuMapper yonghuMapper;
//"文献医案库","古籍文献库","期刊文献库","门诊医案库","学生录入查询"角色共用
    @RequiresPermissions(value = {"文献医案库","古籍文献库","期刊文献库","门诊医案库","学生录入查询"}, logical = Logical.OR)
    @RequestMapping("/zhenghou")
    public List<zhenghou> getZhenghou(){
        return zhenghouMapper.getAll();
    }

    @RequiresPermissions(value = {"文献医案库","古籍文献库","期刊文献库","门诊医案库","学生录入查询"}, logical = Logical.OR)
    @RequestMapping("/zhongyiZhengzhuang")
    public List<zhengzhuang> getzhongyiZhengzhuang(){
        return zhengzhuangMapper.getZhongyao();
    }

    @RequiresPermissions("文献医案库")
    @GetMapping("/")
    public List<yian> getYian(){
        log.info("getYian获取文献医案信息");
        String role = yonghuMapper.getById(subject.getPrincipal().toString()).getType();
        if(role.equals("学生")||role.equals("输入者")){
            return yianMapper.getByUser(subject.getPrincipal().toString());
        }
        return yianMapper.getAll();
    }

    @RequiresPermissions("文献医案库")
    @PostMapping("/")
    public void insertYianMore(@RequestParam("yian") String yianJson,
                               @RequestParam("she") String sheJson,
                               @RequestParam("mai") String maiJson,
                               @RequestParam("zhenghou") String zhenghou,
                               @RequestParam("bingji") String jibing,
                               @RequestParam("zhenduan") String xiyizhenduan,
                               @RequestParam("jiancha") String jianchaJson,
                               @RequestParam(value = "fileArray",required = false) MultipartFile[] xiyifiles,
                               @RequestParam("yao") String chufangJson,
                               @RequestParam(value = "imageCover" ,required = false) MultipartFile imageCover,
                               @RequestParam(value = "imageRight" ,required = false) MultipartFile imageRight,
                               @RequestParam(value = "cankaoFiles",required = false) MultipartFile[] cankaoFiles) throws IOException {
        log.info("insertYianMore添加文献医案start");
        String coverName=null,rightName=null;
        if(imageCover!=null&&!imageCover.isEmpty()){
            coverName=fileLoad(imageCover);
        }
        if(imageRight!=null&&!imageRight.isEmpty()){
            rightName=fileLoad(imageRight);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        yian yian = objectMapper.readValue(yianJson, yian.class);
        yian.setFengmian(coverName);
        yian.setDimian(rightName);
        yian.setCreateuser(subject.getPrincipal().toString());
        yianMapper.insert(yian);
        long yianId = yian.getId();
        if(!sheJson.equals("[]")) {
            loadShe(yianId, sheJson);
        }
        if(!maiJson.equals("[]")) {
            loadMai(yianId, maiJson);
        }
        if(!zhenghou.equals("null,null")) {
            yian_zhengzhuang yian_zhengzhuang = new yian_zhengzhuang();
            yian_zhengzhuang.setYianid((int) yianId);
            yian_zhengzhuang.setZhenghou(zhenghou);
            yian_zhengzhuangMapper.insertOne(yian_zhengzhuang);
        }
        if(!jibing.equals("null,null")) {
            yian_jibing yian_jibing = new yian_jibing();
            yian_jibing.setYianid(yianId);
            yian_jibing.setMingcheng(jibing);
            yian_jibing.setFenglei("中医");
            yian_jibingMapper.insertOne(yian_jibing);
        }
        if(xiyizhenduan!=null&&!xiyizhenduan.equals("")&&!xiyizhenduan.equals(" ")) {
            yian_xiyi yian_xiyi = new yian_xiyi();
            yian_xiyi.setYianid(yianId);
            yian_xiyi.setName(xiyizhenduan);
            yian_xiyiMapper.insertOne(yian_xiyi);
        }
        if(jianchaJson!=null&&!jianchaJson.equals("null")){
            loadJiancha(yianId,jianchaJson,xiyifiles);
        }
        if(chufangJson!=null&&!chufangJson.equals("[]")){
            loadYao(yianId,chufangJson);
        }
        if(cankaoFiles!=null){
            List<yian_cankao> cankaoList = new ArrayList<>();
            for(MultipartFile file:cankaoFiles){
                String name = file.getOriginalFilename();
                String image = fileLoad(file);
                yian_cankao yian_cankao = new yian_cankao();
                yian_cankao.setYianid(yianId);
                yian_cankao.setName(name);
                yian_cankao.setImage(image);
                cankaoList.add(yian_cankao);
            }
            if(!cankaoList.isEmpty()){
                yian_cankaoMapper.insertBatch(cankaoList);
            }
        }
        log.info("insertYianMore添加文献医案end");
    }
    private void loadShe(long yianId,String sheJson){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<JsonNode> jsonNodeList = objectMapper.readValue(sheJson, new TypeReference<List<JsonNode>>() {});
            List<yian_shexiang> yianShexiangList = new ArrayList<>();
            for (JsonNode jsonNode : jsonNodeList) {
                String type = jsonNode.get("type").asText();
                String value = jsonNode.get("value").asText();
                yian_shexiang yian_shexiang = new yian_shexiang();
                yian_shexiang.setYianid(yianId);
                if(type.equals("舌色")){
                    yian_shexiang.setShese(value);
                }
                else if(type.equals("舌态")){
                    yian_shexiang.setShetai(value);
                }
                else if(type.equals("舌形")){
                    yian_shexiang.setShexing(value);
                }
                else if(type.equals("苔质")){
                    yian_shexiang.setTaizhi(value);
                }
                else if(type.equals("苔色")){
                    yian_shexiang.setTaise(value);
                }
                else{
                    yian_shexiang.setName(value);
                }
                yianShexiangList.add(yian_shexiang);
            }
            yian_shexiangMapper.insertBatch(yianShexiangList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void loadMai(long yianId,String maiJson) {
        List<yian_maizhen> yianMaizhenList = new ArrayList<>();
        Pattern pattern = Pattern.compile("\"([^\"]+)\"");
        //正则表达式
        Matcher matcher = pattern.matcher(maiJson);
        while (matcher.find()) {
            String value = matcher.group(1);
            yian_maizhen yian_maizhen =new yian_maizhen();
            yian_maizhen.setName(value);
            yian_maizhen.setYianid(yianId);
            yianMaizhenList.add(yian_maizhen);
        }
        yian_maizhenMapper.insertBatch(yianMaizhenList);
    }
    private void loadJiancha(long yianId,String jianchaJson,MultipartFile[] tupian){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            int imgCount = 0;
            List<JsonNode> jsonNodeList = objectMapper.readValue(jianchaJson, new TypeReference<List<JsonNode>>() {});
            List<yian_jiancha> yianJianchaList = new ArrayList<>();
            for (JsonNode jsonNode : jsonNodeList) {
                String type = jsonNode.get("jianchaxiangmu").asText();
                String time = jsonNode.get("shijian").asText();
                String end = jsonNode.get("jieguo").asText();
                yian_jiancha yianJiancha =new yian_jiancha();
                yianJiancha.setYianid((int) yianId);
                yianJiancha.setJianchaxiangmu(type);
                if(time.equals("null")){
                    yianJiancha.setShijian(null);
                }else {

                    Date date = convertToJavaDate(time);
                    yianJiancha.setShijian(date);
                }
                if(end.equals("null")){
                    yianJiancha.setJieguo(null);
                }else {
                    yianJiancha.setJieguo(end);
                }
                if(tupian!=null&&tupian[imgCount] != null && !tupian[imgCount].isEmpty()){
                    yianJiancha.setTupian(fileLoad(tupian[imgCount]));
                }
                imgCount++;
                yianJianchaList.add(yianJiancha);
            }
            yian_jianchaMapper.insertBatch(yianJianchaList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void loadYao(long yianId,String yaoJson){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<JsonNode> jsonNodeList = objectMapper.readValue(yaoJson, new TypeReference<List<JsonNode>>() {});
            List<yian_chufang> yianChufangList =new ArrayList<>();
            int sortCnt = 0;
            for (JsonNode jsonNode : jsonNodeList) {
                String zhongyao = jsonNode.get("zhongyao").asText();
                String yaoliang = jsonNode.get("yaoliang").asText();
                String paozhi = jsonNode.get("paozhi").asText();
                String chandi = jsonNode.get("chandi").asText();
                String beizhu = jsonNode.get("beizhu").asText();
                String daiding = jsonNode.get("daiding").asText();
                yian_chufang yian_chufang =new yian_chufang();
                yian_chufang.setYianid(yianId);
                yian_chufang.setZhongyaoming(zhongyao);
                if(paozhi.equals("null")){
                    yian_chufang.setPaozhi(null);
                }
                else {
                    yian_chufang.setPaozhi(paozhi);
                }
                if(chandi.equals("null")){
                    yian_chufang.setChandi(null);
                }
                else {
                    yian_chufang.setChandi(chandi);
                }
                if(beizhu.equals("null")){
                    yian_chufang.setBeizhu(null);
                }
                else {
                    yian_chufang.setBeizhu(beizhu);
                }
                if(yaoliang.equals("null")){
                    yian_chufang.setYaoliang(null);
                }
                else {
                    yian_chufang.setYaoliang(yaoliang);
                }
                if(daiding.equals("null")){
                    yian_chufang.setDaiding(null);
                }
                else {
                    yian_chufang.setDaiding(daiding);
                }
                yian_chufang.setSort(sortCnt++);
                yianChufangList.add(yian_chufang);
            }
            yian_chufangMapper.insertBatch(yianChufangList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static Date convertToJavaDate(String input) {
        String inputFormat = "yyyy-MM-dd"; // 输入字符串的格式
        SimpleDateFormat inputFormatter = new SimpleDateFormat(inputFormat);

        try {
            Date date = inputFormatter.parse(input);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
            return null; // 返回 null 表示转换失败
        }
    }
    private String fileLoad(MultipartFile file) throws IOException {
        String fname = file.getOriginalFilename();    //获取原始的文件名
        //用UUID作为新文件名，扩展名不变  避免同名覆盖
        String newName = UUID.randomUUID()+ "." + fname.substring(fname.lastIndexOf(".")+1);
        File dest_file = new File( UPLOADED_FOLDER + newName );
        file.transferTo(dest_file);
        return newName;
    }

private static List<String> sheSe = new ArrayList<>(),sheXing = new ArrayList<>(),sheTai = new ArrayList<>(),taiZhi =new ArrayList<>(),taiSe = new ArrayList<>();
    static {
        sheSe.add("淡");sheSe.add("绛");sheSe.add("尖红");sheSe.add("淡红");sheSe.add("暗");sheSe.add("尖微红");
        sheSe.add("淡白");sheSe.add("暗红");sheSe.add("边尖红");sheSe.add("红");sheSe.add("紫");sheSe.add("根微黄");
        sheSe.add("红绛");sheSe.add("淤点");sheSe.add("根微腻");

        sheXing.add("胖大");sheXing.add("瘦薄");sheXing.add("点刺");sheXing.add("裂纹");sheXing.add("齿痕");

        sheTai.add("歪斜");sheTai.add("颤动");sheTai.add("吐弄");sheTai.add("短缩");sheTai.add("麻痹");

        taiZhi.add("苔薄");taiZhi.add("苔厚");taiZhi.add("苔润");taiZhi.add("苔燥");taiZhi.add("苔腻");taiZhi.add("苔腐");
        taiZhi.add("剥落");   taiZhi.add("水滑");

        taiSe.add("白苔");taiSe.add("黄苔");taiSe.add("灰苔");taiSe.add("黑苔");
    }

    @RequiresPermissions("文献医案库")
    @PostMapping("/batch/")
    public ResponseEntity<String> insertBatch(@RequestParam("file") MultipartFile file) {
        log.info("insertBatch文献医案批量导入");
        try {
            // 校验文件类型，只接受 .xls 和 .xlsx 格式的文件
            if (!file.getOriginalFilename().endsWith(".xls") && !file.getOriginalFilename().endsWith(".xlsx")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unsupported file format. Please upload an Excel file.");
            }
            // 使用 Apache POI 解析 Excel 文件并提取数据
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                if (row.getRowNum() == 0) { // 跳过表头行
                    continue;
                }
                yian yian = new yian();
                yian_xiyi yian_xiyi =null;
                yian_jibing yian_jibing = null;
                List<yian_shexiang> yianShexiangList = null;
                List<yian_maizhen> yian_maizhenList = null;
                List<yian_chufang> yianChufangList = null;
                for(int i=0;i<=11;++i){
                    String value=null;
                    Cell cell= row.getCell(i);
                    if(cell!=null){
                        CellType cellType=cell.getCellType();
                        value = switch (cellType) {
                            case STRING ->
                                // 处理字符串类型的单元格
                                    cell.getStringCellValue();
                            case NUMERIC ->
                                // 处理数值类型的单元格
                                    String.valueOf((int)cell.getNumericCellValue());
                            default -> null;
                        };
                    }
                    switch (i) {
                        case 0 :
                            if(value==null){
                                return ResponseEntity.ok().body("{\"message\": \"文件提交成功!\"}");
                            }yian.setXingming(value);break;
                        case 1 :yian.setXingbie(value);break;
                        case 2 :yian.setNianling(value);break;
                        case 3 :yian.setJiuzhenyisheng(value);break;
                        case 4 :{
                            if(value==null){
                                break;
                            }
                            log.info("日期字符串数据    "+value);
                            String regex = "(\\d{4})-(\\d{2})-(\\d{2})"; // 正则表达式匹配日期格式

                            Pattern pattern = Pattern.compile(regex);
                            Matcher matcher = pattern.matcher(value);

                            if (matcher.matches()) {
                                String year = matcher.group(1); // 匹配的第一个组，对应yyyy
                                String month = matcher.group(2); // 匹配的第二个组，对应MM
                                String day = matcher.group(3); // 匹配的第三个组，对应dd
                                yian.setYear(year);
                                yian.setMonth(month);
                                yian.setDay(day);
                            } else {
                                log.info("日期字符串格式不匹配");
                                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unsupported format. Please check values.");
                            }
                            break;
                        }

                        case 5 :{
                            if(value==null){
                                break;
                            }
                            yian_xiyi = new yian_xiyi();
                            yian_xiyi.setName(value);break;
                        }
                        case 6 :{
                            if(value==null){
                                break;
                            }
                            yian_jibing = new yian_jibing();
                            yian_jibing.setMingcheng(value);
                            yian_jibing.setFenglei("中药");
                        }
                        case 7:yian.setXianbingshi(value);break;
                        case 8:{
                            if(value==null){
                                break;
                            }
                            String[] she = value.split("，");
                            yianShexiangList = new ArrayList<>();
                            for(String x : she){
                                yian_shexiang yian_shexiang = new yian_shexiang();
                                if(sheSe.contains(x)){
                                    yian_shexiang.setShese(x);
                                }
                                else if(sheXing.contains(x)){
                                    yian_shexiang.setShexing(x);
                                }
                                else if(sheTai.contains(x)){
                                    yian_shexiang.setShetai(x);
                                }
                                else if(taiZhi.contains(x)){
                                    yian_shexiang.setTaizhi(x);
                                }
                                else if(taiSe.contains(x)){
                                    yian_shexiang.setTaise(x);
                                }
                                else {
                                    yian_shexiang.setName(x);
                                }
                                yianShexiangList.add(yian_shexiang);
                            }
                            break;
                        }
                        case 9:{
                            if(value==null){
                                break;
                            }
                            yian_maizhenList =new ArrayList<>();
                            String[] mai =value.split("，");
                            for(String x : mai){
                                yian_maizhen yian_maizhen = new yian_maizhen();
                                yian_maizhen.setName(x);
                                yian_maizhenList.add(yian_maizhen);
                            }
                            break;
                        }
                        case 10:{
                            if(value==null){
                                break;
                            }
                            String[] chufang = value.split("，");
                            yianChufangList =new ArrayList<>();
                            int cnt = 0;
                            for(String x : chufang){
                                String ming,liang;
                                String regex = "^(.*?)(\\d+)g$"; // 正则表达式匹配格式

                                Pattern pattern = Pattern.compile(regex);
                                Matcher matcher = pattern.matcher(x);

                                if (matcher.matches()) {
                                    ming= matcher.group(1); // 匹配的第一个组，对应x
                                    liang = matcher.group(2); // 匹配的第二个组，对应y
                                } else {
                                    log.info("处方字符串格式不匹配");
                                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unsupported format. Please check values.");
                                }

                                yian_chufang yian_chufang = new yian_chufang();
                                yian_chufang.setZhongyaoming(ming);
                                yian_chufang.setYaoliang(liang+'克');
                                yian_chufang.setSort(cnt++);
                                yianChufangList.add(yian_chufang);
                            }
                            break;
                        }
                        case 11:
                            yian.setJishu(value);break;
                    }

                }
                yian.setBiaohao(getDate());
                yian.setShenhe("保存");
                yian.setCreateuser(subject.getPrincipal().toString());
                yianMapper.insert(yian);
                long yianId = yian.getId();
                if(yian_xiyi!=null){
                    yian_xiyi.setYianid(yianId);
                    yian_xiyiMapper.insertOne(yian_xiyi);
                }
                if(yian_jibing!=null){  //实际上是yian_zhongyao，原先给的数据库表结构太乱
                    yian_jibing.setYianid(yianId);
                    yian_jibingMapper.insertOne(yian_jibing);
                }
                if(yianShexiangList!=null){
                    for(int i =0 ;i<yianShexiangList.size();++i){
                        yianShexiangList.get(i).setYianid(yianId);
                    }
                    yian_shexiangMapper.insertBatch(yianShexiangList);
                }
                if(yian_maizhenList!=null){
                    for(int i =0 ;i<yian_maizhenList.size();++i){
                        yian_maizhenList.get(i).setYianid(yianId);
                    }
                    yian_maizhenMapper.insertBatch(yian_maizhenList);
                }
                if(yianChufangList!=null){
                    for(int i =0 ;i<yianChufangList.size();++i){
                        yianChufangList.get(i).setYianid(yianId);
                    }
                    yian_chufangMapper.insertBatch(yianChufangList);
                }
            }

            return ResponseEntity.ok().body("{\"message\": \"文件提交成功!\"}");
        } catch (Exception e) {
            e.printStackTrace(); // 添加错误日志
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"message\": \"发生错误！请联系管理员！\"}");
        }
    }

    private String getDate(){
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        String formattedDateTime = dateFormat.format(now);
        long currentTimeMillis = System.currentTimeMillis();
        int milliseconds = (int) (currentTimeMillis % 10000); // Get the last 4 digits
        String formattedMilliseconds = String.format("%04d", milliseconds);
        return formattedDateTime + formattedMilliseconds;
    }

    @RequiresPermissions(value = {"文献医案库","古籍文献库","期刊文献库","门诊医案库","学生录入查询"}, logical = Logical.OR)
    @PutMapping("/shenhe")
    public void shenhe(@RequestParam("id") long id,
                       @RequestParam("shenhe") String shenhe,
                       @RequestParam("score") String score){
        log.info("shenhe修改医案审核信息");
        yian yian = new yian();
        yian.setShenhe(shenhe);
        yian.setId(id);
        if(shenhe.equals("一审")){
            yian.setFirstcheckfenshu(score);
            //人占位
            yian.setFirstcheckuser(subject.getPrincipal().toString());
            yianMapper.updateYs(yian);
        }
        else {
            yian.setFirstcheckfenshu(score);
            //人占位
            yian.setSecondcheckuser(subject.getPrincipal().toString());
            yianMapper.updateEs(yian);
        }
    }

    @RequiresPermissions(value = {"文献医案库","学生录入查询"}, logical = Logical.OR)
    @PutMapping("/")
    public void update(@RequestParam("yian") String yianJson,
                       @RequestParam("she") String sheJson,
                       @RequestParam("mai") String maiJson,
                       @RequestParam("zhenghou") String zhenghou,
                       @RequestParam("bingji") String jibing,
                       @RequestParam("zhenduan") String xiyizhenduan,
                       @RequestParam("jiancha") String jianchaJson,
                       @RequestParam(value = "fileArray",required = false) MultipartFile[] xiyifiles,
                       @RequestParam("yao") String chufangJson,
                       @RequestParam(value = "imageCover" ,required = false) MultipartFile imageCover,
                       @RequestParam(value = "imageRight" ,required = false) MultipartFile imageRight,
                       @RequestParam(value = "cankaoFiles",required = false) MultipartFile[] cankaoFiles) throws IOException {
        log.info("update修改文献医案start");
        String coverName=null,rightName=null;
        ObjectMapper objectMapper = new ObjectMapper();
        yian yian = objectMapper.readValue(yianJson, yian.class);
        long yianId = yian.getId();
        yianMapper.update(yian);
        if(imageCover!=null&&!imageCover.isEmpty()){
            yian fengmian = new yian();
            coverName=fileLoad(imageCover);
            fengmian.setFengmian(coverName);
            fengmian.setId(yianId);
            yianMapper.updateFm(fengmian);
        }
        if(imageRight!=null&&!imageRight.isEmpty()){
            yian dimian = new yian();
            rightName=fileLoad(imageRight);
            dimian.setDimian(rightName);
            dimian.setId(yianId);
            yianMapper.updateDm(dimian);
        }
        deleteOthers(yianId);  //先删除再插入信息
        if(!sheJson.equals("[]")) {
            loadShe(yianId, sheJson);
        }
        if(!maiJson.equals("[]")) {
            loadMai(yianId, maiJson);
        }
        if(!zhenghou.equals("null,null")) {
            yian_zhengzhuang yian_zhengzhuang = new yian_zhengzhuang();
            yian_zhengzhuang.setYianid((int) yianId);
            yian_zhengzhuang.setZhenghou(zhenghou);
            yian_zhengzhuangMapper.insertOne(yian_zhengzhuang);
        }
        if(!jibing.equals("null,null")) {
            yian_jibing yian_jibing = new yian_jibing();
            yian_jibing.setYianid(yianId);
            yian_jibing.setMingcheng(jibing);
            yian_jibing.setFenglei("中医");
            yian_jibingMapper.insertOne(yian_jibing);
        }
        if(xiyizhenduan!=null&&!xiyizhenduan.equals("")&&!xiyizhenduan.equals(" ")) {
            yian_xiyi yian_xiyi = new yian_xiyi();
            yian_xiyi.setYianid(yianId);
            yian_xiyi.setName(xiyizhenduan);
            yian_xiyiMapper.insertOne(yian_xiyi);
        }
        if(jianchaJson!=null&&!jianchaJson.equals("null")){
            loadJiancha(yianId,jianchaJson,xiyifiles);
        }
        if(chufangJson!=null&&!chufangJson.equals("[]")){
            loadYao(yianId,chufangJson);
        }
        if(cankaoFiles!=null){
            List<yian_cankao> cankaoList = new ArrayList<>();
            for(MultipartFile file:cankaoFiles){
                String name = file.getOriginalFilename();
                String image = fileLoad(file);
                yian_cankao yian_cankao = new yian_cankao();
                yian_cankao.setYianid(yianId);
                yian_cankao.setName(name);
                yian_cankao.setImage(image);
                cankaoList.add(yian_cankao);
            }
            if(!cankaoList.isEmpty()){
                yian_cankaoMapper.insertBatch(cankaoList);
            }
        }
        log.info("update修改文献医案end");
    }
    private void deleteOthers(long yianId ){  //删除除了yian表以外的表信息
        List<yian_cankao> cankaoList = yian_cankaoMapper.getByYianId(yianId);
        for(yian_cankao x : cankaoList){
            deleteFile(x.getImage());
        }
        yian_cankaoMapper.deleteByYianId(yianId);
        yian_chufangMapper.deleteByYianId(yianId);
        yian_jianchaMapper.deleteByYianId(yianId);
        yian_jibingMapper.deleteByYianId(yianId);
        yian_maizhenMapper.deleteByYianId(yianId);
        yian_shexiangMapper.deleteByYianId(yianId);
        yian_xiyiMapper.deleteByYianId(yianId);
        yian_zhengzhuangMapper.deleteByYianId(yianId);
    }


    private void deleteFile(String name){
        String path = UPLOADED_FOLDER + name;
        File imageFile = new File(path);
        // 检查文件是否存在并且是一个文件
        if (imageFile.exists() && imageFile.isFile()) {
            // 尝试删除文件
            if (imageFile.delete()) {
                log.info("图片文件删除成功！");
            } else {
                log.info("图片文件删除失败！");
            }
        } else {
            log.info("图片文件不存在！");
        }
    }

    @RequiresPermissions(value = {"文献医案库","学生录入查询"}, logical = Logical.OR)
    @DeleteMapping("/{id}")
    public void deleteYian(@PathVariable long id){
        log.info("deleteYian文献医案删除");
        yianMapper.deleteById(id);
    }

    private static final String API_KEY = "cee9Oy0yNzCPuzhIqPUkRwKq";
    private static final String SECRET_KEY = "zh82H5Ukx6VPtcdrGeoy1O5NpxddMopg";
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

//    @RequiresPermissions("文献医案库")
    @PostMapping("/ocr")
    private String OCR(@RequestParam MultipartFile img) {
        log.info("接收到了OCR请求");
        try {
            // image 可以通过 getFileContentAsBase64 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
            String base64Data = getFileContentAsBase64(img,true);
            String result = getStringByJson(oncrPerform(base64Data));
            log.info(result);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private String getStringByJson(String jsonStr){
        // 解析JSON字符串
        JSONObject jsonObject = new JSONObject(jsonStr);
        JSONArray wordsResultArray = jsonObject.getJSONArray("words_result");
        // 创建一个StringBuilder来存储提取的words字段
        StringBuilder wordsStringBuilder = new StringBuilder();
        // 遍历wordsResultArray并提取words字段
        for (int i = 0; i < wordsResultArray.length(); i++) {
            JSONObject wordObject = wordsResultArray.getJSONObject(i);
            String word = wordObject.getString("words");
            // 将提取的word字段追加到StringBuilder中，用空格连接
            wordsStringBuilder.append(word).append(" ");
        }
        // 最后的结果字符串
        return wordsStringBuilder.toString().trim();
    }
    private String getFileContentAsBase64(MultipartFile file, boolean urlEncode) throws IOException {
        byte[] fileBytes = file.getBytes();
        String base64 = Base64.getEncoder().encodeToString(fileBytes);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }
    private String oncrPerform(String base64Img) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "image=" + base64Img);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBodyString = response.body().string(); // 保存响应内容

        log.info(responseBodyString);
        return responseBodyString;
    }

    private String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBodyString = response.body().string(); // 保存响应内容

        return new JSONObject(responseBodyString).getString("access_token");
    }
}





